$(function () {
    // loadKeyWords();
    loadTable();
});
var table;

function loadKeyWords() {
    var url = baseQuestionUrl + "list/keyWords?start=0&limit=1000000";
    $.ajax(ajaxCommon.buildLoadingOption({
        url: url,
        headers: {
            "authorization": 'Bearer ' + getCookie(cookieName)
        },
        type: "GET",
        contentType: "application/json",
        success: function (data) {
            loadTable(data.data.rows);
        }
    }));
}

function loadTable() {
    table = $("#keyWordsTable").DataTable({
        ajax: {
            url: baseQuestionUrl + "list/keyWords",
            headers: {
                "authorization": 'Bearer ' + getCookie(cookieName)
            },
            type: "GET",
            contentType: "application/json",
            data: function (req) {
                req.limit = req.length;
                req.search = req.search.value;
            },
            dataSrc: function (res) {
                if(res.code===200&&res.data) {
                    res.recordsTotal = res.data.total;
                    res.recordsFiltered = res.data.total;
                    return res.data.rows;
                }
            },
            error: function (request, error) {
                if (request.status === 401) {
                    $(location).attr('href', 'login.html');
                } else {
                    swal("失败",'','error');
                }
            }
        },
        serverSide: true,
        bLengthChange: false,
        // data: data,
        // destroy: true,
        searching: true,
        ordering: false,
        select: true,
        columns: [
            {data: 'keyword'},
            {
                data: 'activity',
                render: function (data, type, row, meta) {
                    if(row) {
                        if (row.actived === 1) {
                            return "启用";
                        } else {
                            return "未启用";
                        }
                    }
                }
            }
        ],
        pagingType: "full_numbers",
        language: {
            sProcessing: "处理中...",
            sLengthMenu: "显示 _MENU_ 项结果",
            sZeroRecords: "没有匹配结果",
            sInfo: "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
            sInfoEmpty: "显示第 0 至 0 项结果，共 0 项",
            sInfoFiltered: "(由 _MAX_ 项结果过滤)",
            sInfoPostFix: "",
            sSearch: "搜索:",
            sUrl: "",
            sEmptyTable: "表中数据为空",
            sLoadingRecords: "载入中...",
            sInfoThousands: ",",
            oPaginate: {
                sFirst: "首页",
                sPrevious: "上页",
                sNext: "下页",
                sLast: "末页"
            },
            oAria: {
                "sSortAscending": ": 以升序排列此列",
                "sSortDescending": ": 以降序排列此列"
            }
        },
        columnDefs: [
            // {orderable: false, targets: 0},
            {
                targets: 2,
                render: function (data, type, row, meta) {
                    if(row) {
                        if (row.actived === 1) {
                            return "";
                        } else {
                            return "<button type='button' class='btn btn-danger' style='border: 1px solid red;color: red;background: transparent;' onclick='showDelete(" + JSON.stringify(row) + ");'>删除</button>";
                        }
                    }
                }
            }]
    });
}

/**
 * 新增一个关键字
 */
function addKeyword() {
    var keyWord = $("#keyword").val();
    if (isNull(keyWord)) {
        swal("输入关键字");
        return;
    }
    if (keyWord.match(new RegExp("[\s]", "g"))) {
        swal("关键字格式不正确");
        return;
    }
    var data = {"keyWord": keyWord};
    var url = baseQuestionUrl + "add/keyWord";
    $.ajax(ajaxCommon.buildLoadingOption({
        url: url,
        headers: {
            "authorization": 'Bearer ' + getCookie(cookieName)
        },
        data: JSON.stringify(data),
        type: "POST",
        contentType: "application/json",
        success: function (data) {
            $('#addModal').modal('toggle');
            $('#keyword').val('');
            if (!data.data) {
                swal("新增失败",'','error');
            } else {
                swal("新增成功",'','success');
                table.ajax.reload();
            }
        },
        error: function (request, error) {
            $('#addModal').modal('toggle');
            $('#keyword').val('')
            if (request.status === 401) {
                $(location).attr('href', 'login.html');
            } else {
                swal("失败",'','error');
            }
        }
    }));
}

function showDelete(keyWord) {
    swal({
        title: "删除关键字",
        text: "确认要删除该关键字吗？",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#337ab7",
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        closeOnConfirm: true,
        closeOnCancel: true
    },function(isConfirm) {
        if (isConfirm) {
            var url = baseQuestionUrl + "delete/keyWord/" + keyWord.id;
            ajaxCommon.request('get',url,{},function (res) {
                console.log(res);
                if(res.code===200) {
                    swal("删除！", "当前记录已被删除！", "success");
                    table.ajax.reload();
                }
            })
        }
    })
}

/**
 * 删除一个未启用的关键字
 * @param id
 */
function deleteKeyWord(id) {
    swal({
            title: "删除未匹配问题",
            text: "确认要删除未匹配问题？",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#337ab7",
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            closeOnConfirm: false,
            closeOnCancel: true
        },
        function(isConfirm) {
            if (isConfirm) {
                var url = baseQuestionUrl + "delete/keyWord/" + id;
                ajaxCommon.request('get', url, {},function (res) {
                    if(res.code===200) {
                        swal("删除！", "当前记录已被删除！", "success");
                        table.ajax.reload();
                    }
                })
            }
        })
}

function editKeyword () {
    $('#keyword').val('')
    $('#addModal').modal('toggle');
}
